'use strict';
const path = require('path');
const Package = require('@zmz-cli-dev/package');
const log = require('@zmz-cli-dev/log');
const { exec: spawn } = require('@zmz-cli-dev/utils');
const SETTINGS = {
  'init': '@zmz-cli-dev/init'
}
async function exec() {
  let pkg = null
  let targetPath = process.env.CLI_TARGET_PATH
  const homePath = process.env.CLI_HOME_PATH
  const cmdObj = arguments[arguments.length - 1]
  const packageName = SETTINGS[cmdObj.name()]
  const packageVersion = 'latest'
  if (!targetPath) {
    targetPath = path.resolve(homePath, 'dependencies') // 默认安装到这个目录下
    const storeDir = path.resolve(targetPath, 'node_modules') // node_modules目录
    pkg = new Package({
      targetPath,
      storeDir,
      packageName,
      packageVersion
    })
    if(await pkg.exists()) { // 如果包存在，则更新pkg
      await pkg.update() 
    }else{ // 如果包不存在，则安装pkg
      await pkg.install() 
    }
  } else {
    pkg = new Package({
      targetPath,
      packageName,
      packageVersion
    })
  }
  console.log(pkg)
  const rootFile = pkg.getRootFilePath()
  console.log('rootFile', rootFile)
  if (rootFile) {
    try {
      // 在当前进程中调用
      // require(rootFile).apply(null, arguments)
      // require(rootFile)(Array.from(arguments))
      // 在node子进程中调用
      const args = Array.from(arguments)
      const cmd = args[args.length - 1]
      const o = Object.create(null)
      Object.keys(cmd).forEach(key => {
        if(cmd.hasOwnProperty(key) && !key.startsWith('_') && key !== 'parent'){
          o[key] = cmd[key]
        }
      })
      args[args.length - 1] = o
      const code = `require('${rootFile}')(${JSON.stringify(args)})`
      const child = spawn('node', ['-e', code], {
        cwd: process.cwd(), // 当前命令执行的路径
        stdio: 'inherit' // 子进程的输出流
      })
      child.on('error', e => {
        // log.error(e.message)
        process.exit(1) // exit 通常用于终止当前的Node.js进程, 其中 0 通常表示成功退出，而非零值表示出现了错误
      })
      child.on('exit', code => {
        // log.verbose('命令执行结果', code)
        process.exit(code)
      })
    } catch (err) {
      log.error(err.message);
    }
  }
}



module.exports = exec;

